<template>
    <div class="tag-selector">
        <div class="selector-header">
            <h4>Tags</h4>
            <span class="tag-count">{{ selectedTags.length }}/{{ maxTags }}</span>
        </div>

        <!-- 输入新标签 -->
        <div class="tag-input">
            <van-field v-model="inputTag" placeholder="Add a tag..." @keyup.enter="addTag" @blur="addTag"
                maxlength="20">
                <template #button>
                    <van-button size="small" type="primary" @click="addTag" :disabled="!canAddTag">
                        Add
                    </van-button>
                </template>
            </van-field>
        </div>

        <!-- 已选标签 -->
        <div class="selected-tags" v-if="selectedTags.length > 0">
            <h5>Selected Tags</h5>
            <div class="tags-list">
                <van-tag v-for="tag in selectedTags" :key="tag" closeable type="primary" @close="removeTag(tag)">
                    {{ tag }}
                </van-tag>
            </div>
        </div>

        <!-- 推荐标签 -->
        <div class="recommended-tags" v-if="recommendedTags.length > 0">
            <h5>Recommended</h5>
            <div class="tags-list">
                <van-tag v-for="tag in availableRecommendedTags" :key="tag" plain @click="selectRecommendedTag(tag)">
                    {{ tag }}
                </van-tag>
            </div>
        </div>

        <!-- 热门标签 -->
        <div class="popular-tags" v-if="popularTags.length > 0">
            <h5>Popular Tags</h5>
            <div class="tags-list">
                <van-tag v-for="tag in availablePopularTags" :key="tag.name" plain
                    @click="selectRecommendedTag(tag.name)">
                    {{ tag.name }}
                    <span class="tag-count-badge">{{ tag.count }}</span>
                </van-tag>
            </div>
        </div>

        <!-- 分类标签 -->
        <div class="category-tags">
            <van-collapse v-model="activeCategories">
                <van-collapse-item v-for="category in tagCategories" :key="category.name" :title="category.name"
                    :name="category.name">
                    <div class="tags-list">
                        <van-tag v-for="tag in getAvailableCategoryTags(category.tags)" :key="tag" plain
                            @click="selectRecommendedTag(tag)">
                            {{ tag }}
                        </van-tag>
                    </div>
                </van-collapse-item>
            </van-collapse>
        </div>

        <!-- 标签建议弹窗 -->
        <van-popup v-model:show="showSuggestions" position="bottom" round>
            <div class="suggestions-popup">
                <div class="popup-header">
                    <h3>Tag Suggestions</h3>
                    <van-icon name="cross" @click="showSuggestions = false" />
                </div>
                <div class="popup-content">
                    <p>Based on your content, we suggest these tags:</p>
                    <div class="suggested-tags">
                        <van-tag v-for="tag in contentSuggestions" :key="tag" type="success" plain
                            @click="selectSuggestedTag(tag)">
                            {{ tag }}
                        </van-tag>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { showToast } from 'vant'

interface TagCategory {
    name: string
    tags: string[]
}

interface PopularTag {
    name: string
    count: number
}

interface Props {
    modelValue: string[]
    maxTags?: number
    contentText?: string // 用于生成智能建议
}

interface Emits {
    (e: 'update:modelValue', tags: string[]): void
}

const props = withDefaults(defineProps<Props>(), {
    maxTags: 10
})

const emit = defineEmits<Emits>()

// 响应式数据
const selectedTags = ref<string[]>([...props.modelValue])
const inputTag = ref('')
const activeCategories = ref<string[]>([])
const showSuggestions = ref(false)

// 推荐标签
const recommendedTags = ref<string[]>([
    'communication', 'workplace', 'interview', 'presentation',
    'networking', 'confidence', 'social-skills'
])

// 热门标签
const popularTags = ref<PopularTag[]>([
    { name: 'workplace', count: 1234 },
    { name: 'interview', count: 987 },
    { name: 'presentation', count: 756 },
    { name: 'networking', count: 543 },
    { name: 'confidence', count: 432 },
    { name: 'team-work', count: 321 }
])

// 分类标签
const tagCategories = ref<TagCategory[]>([
    {
        name: 'Skills',
        tags: ['communication', 'leadership', 'teamwork', 'presentation', 'negotiation', 'listening']
    },
    {
        name: 'Scenarios',
        tags: ['workplace', 'interview', 'meeting', 'networking', 'social-event', 'phone-call']
    },
    {
        name: 'Emotions',
        tags: ['confidence', 'anxiety', 'stress', 'nervousness', 'excitement', 'calm']
    },
    {
        name: 'Difficulty',
        tags: ['beginner', 'intermediate', 'advanced', 'expert', 'challenging', 'easy']
    }
])

// 内容建议标签
const contentSuggestions = ref<string[]>([])

// 计算属性
const canAddTag = computed(() => {
    const tag = inputTag.value.trim().toLowerCase()
    return tag.length > 0 &&
        !selectedTags.value.includes(tag) &&
        selectedTags.value.length < props.maxTags
})

const availableRecommendedTags = computed(() => {
    return recommendedTags.value.filter(tag => !selectedTags.value.includes(tag))
})

const availablePopularTags = computed(() => {
    return popularTags.value.filter(tag => !selectedTags.value.includes(tag.name))
})

// 方法
const getAvailableCategoryTags = (tags: string[]) => {
    return tags.filter(tag => !selectedTags.value.includes(tag))
}

const addTag = () => {
    const tag = inputTag.value.trim().toLowerCase()

    if (!tag) return

    if (selectedTags.value.includes(tag)) {
        showToast('Tag already added')
        return
    }

    if (selectedTags.value.length >= props.maxTags) {
        showToast(`Maximum ${props.maxTags} tags allowed`)
        return
    }

    selectedTags.value.push(tag)
    inputTag.value = ''
    emit('update:modelValue', selectedTags.value)
}

const removeTag = (tag: string) => {
    const index = selectedTags.value.indexOf(tag)
    if (index > -1) {
        selectedTags.value.splice(index, 1)
        emit('update:modelValue', selectedTags.value)
    }
}

const selectRecommendedTag = (tag: string) => {
    if (selectedTags.value.includes(tag)) {
        showToast('Tag already added')
        return
    }

    if (selectedTags.value.length >= props.maxTags) {
        showToast(`Maximum ${props.maxTags} tags allowed`)
        return
    }

    selectedTags.value.push(tag)
    emit('update:modelValue', selectedTags.value)
}

const selectSuggestedTag = (tag: string) => {
    selectRecommendedTag(tag)
    // 从建议中移除已选择的标签
    const index = contentSuggestions.value.indexOf(tag)
    if (index > -1) {
        contentSuggestions.value.splice(index, 1)
    }
}

const generateContentSuggestions = (text: string) => {
    if (!text || text.length < 10) {
        contentSuggestions.value = []
        return
    }

    const suggestions: string[] = []
    const lowerText = text.toLowerCase()

    // 基于关键词的简单匹配
    const keywordMap: Record<string, string[]> = {
        'work': ['workplace', 'professional', 'career'],
        'job': ['interview', 'career', 'workplace'],
        'interview': ['interview', 'job-search', 'career'],
        'presentation': ['presentation', 'public-speaking', 'communication'],
        'meeting': ['meeting', 'workplace', 'teamwork'],
        'team': ['teamwork', 'collaboration', 'workplace'],
        'speak': ['public-speaking', 'communication', 'presentation'],
        'confident': ['confidence', 'self-esteem', 'assertiveness'],
        'nervous': ['anxiety', 'nervousness', 'stress'],
        'social': ['social-skills', 'networking', 'communication']
    }

    Object.entries(keywordMap).forEach(([keyword, tags]) => {
        if (lowerText.includes(keyword)) {
            tags.forEach(tag => {
                if (!suggestions.includes(tag) && !selectedTags.value.includes(tag)) {
                    suggestions.push(tag)
                }
            })
        }
    })

    contentSuggestions.value = suggestions.slice(0, 5)

    if (suggestions.length > 0) {
        showSuggestions.value = true
    }
}

// 监听内容变化生成建议
watch(() => props.contentText, (newText) => {
    if (newText) {
        generateContentSuggestions(newText)
    }
}, { immediate: true })

// 监听外部标签变化
watch(() => props.modelValue, (newTags) => {
    selectedTags.value = [...newTags]
}, { deep: true })
</script>

<style lang="scss" scoped>
.tag-selector {
    .selector-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h4 {
            font-size: 16px;
            color: #323233;
            margin: 0;
            font-weight: 500;
        }

        .tag-count {
            font-size: 12px;
            color: #969799;
        }
    }

    .tag-input {
        margin-bottom: 20px;
    }

    .selected-tags,
    .recommended-tags,
    .popular-tags {
        margin-bottom: 20px;

        h5 {
            font-size: 14px;
            color: #323233;
            margin: 0 0 12px 0;
            font-weight: 500;
        }

        .tags-list {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;

            .van-tag {
                cursor: pointer;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }

                .tag-count-badge {
                    margin-left: 4px;
                    font-size: 10px;
                    opacity: 0.7;
                }
            }
        }
    }

    .category-tags {
        .tags-list {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            padding: 12px 0;

            .van-tag {
                cursor: pointer;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }
}

.suggestions-popup {
    padding: 20px;

    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h3 {
            font-size: 18px;
            color: #323233;
            margin: 0;
            font-weight: 600;
        }

        .van-icon {
            color: #969799;
            cursor: pointer;
        }
    }

    .popup-content {
        p {
            font-size: 14px;
            color: #646566;
            margin: 0 0 16px 0;
            line-height: 1.5;
        }

        .suggested-tags {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;

            .van-tag {
                cursor: pointer;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }
}
</style>